package 多线程;




import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * @Author: 朱胜伟
 * @CreateTime: 2021-02-03 10:14
 * @Description: 通过管道实现线程间的通信
 */
public class PipeStreamTest {

    public static void main(String[] args) {
        PipedInputStream inputStream = new PipedInputStream();
        PipedOutputStream outputStream = new PipedOutputStream();
        try {
            inputStream.connect(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                writeData(outputStream);
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                readData(inputStream);
            }
        }).start();

    }

    public static void writeData(PipedOutputStream out){
        //分别把0-10写入到管道
        try {
            for (int i = 0; i < 100; i++) {
                out.write((""+i).getBytes());
            }
            out.close(); //关闭管道流
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //定义方法从管道流中读取数据
    public static void readData(PipedInputStream in){
        byte[] bytes = new byte[1024];
        try {
            int len = in.read(bytes);
            while (len != -1){
                System.out.println(new String(bytes,0,len));
                len = in.read(bytes);
            }
            in.close();
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}

